package com.summer.NIO;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * scatter/gather**/
public class ChannelCase2 {
	public static void main(String[] args) throws IOException {
		// 为了以可读可写的方式打开文件，这里使用RandomAccessFile来创建文件。  
        @SuppressWarnings("resource")
		FileChannel fc = new RandomAccessFile("scatter.dat", "rw").getChannel();  
        
//        ByteBuffer header = ByteBuffer.allocate(128);
//        ByteBuffer body   = ByteBuffer.allocate(1024);
        
//        header.put("msg:这个事一条消息头·。。。".getBytes());
//        body.put("text:这个事一条消息内容，内容是从前有座山山上有座庙庙里有个和尚和尚在讲故事故事的内容是从浅。。。".getBytes());
//        
//        //write data into buffers
//        ByteBuffer[] bufferArray = { header, body };
//        //写入前一定要先切换读取模式否则会出错
//        header.flip();
//        body.flip();
//        
//        long size = fc.write(bufferArray);
//        System.out.println("size:"+size);
        
		ByteBuffer header = ByteBuffer.allocate(128); 
		ByteBuffer body   = ByteBuffer.allocate(1024); 
		ByteBuffer[] bufferArray = { header, body }; 
		fc.read(bufferArray);
		
		byte[] headerByte = new byte[header.limit()];
		header.flip();
		header.get(headerByte, 0, headerByte.length);
		
		byte[] bodyByte = new byte[body.limit()];
		body.flip();
		body.get(bodyByte, 0, bodyByte.length);
		
		System.out.println("header:"+new String(headerByte));
		System.out.println("body:"+new String(bodyByte));
		
        fc.close(); 
	}
}
